from fastapi import APIRouter, Query,UploadFile
from tortoise.expressions import Q
from app.controllers.orders.car import orders_car_controller
from app.schemas.base import Success, SuccessExtra,Fail
from app.schemas.orders import *
from app.core.dependency import DependCustomerAuth
from app.core.ctx import CTX_USER_ID
from app.models.goods import Goods
import json
mini_orders_car_router = APIRouter()
model_name = "购物车"



@mini_orders_car_router.get("/list", summary=f"查看{model_name}列表", dependencies=[DependCustomerAuth])
async def do_orders_receive_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
):
    user_id = CTX_USER_ID.get()
    q = Q(user_id=user_id)
    total, data = await orders_car_controller.do_list(page=page, page_size=page_size, search=q)
    goods_ids = {orders['goods_id'] for orders in data}  # 获取所有的 goods_id
    goods = await Goods.filter(id__in=goods_ids)
    goods_dict1 = {good.id: good.name for good in goods}
    goods_dict2 = {good.id: good.cover for good in goods}
    for car in data:
        car['name'] = goods_dict1.get(car['goods_id'], "")
        car['cover'] = goods_dict2.get(car['goods_id'], "")
        car['checked'] = False
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)


@mini_orders_car_router.post("/create", summary=f"创建{model_name}", dependencies=[DependCustomerAuth])
async def do_orders_receive_create(
        data_in: OrdersCarCreate,
):
    user_id = CTX_USER_ID.get()
    data_in.user_id = user_id
    await orders_car_controller.do_create(obj_in=data_in)
    return Success(msg="创建成功")

@mini_orders_car_router.post("/update", summary=f"更新{model_name}", dependencies=[DependCustomerAuth])
async def do_orders_receive_update(
        data_in: OrdersCarUpdate,
):
    user_id = CTX_USER_ID.get()
    data_in.user_id = user_id
    ret = await orders_car_controller.do_update(obj_in=data_in)
    if ret:
        return Success(msg="更新成功")
    else:
        return Fail(msg="库存不足")

@mini_orders_car_router.get("/delete", summary=f"删除{model_name}", dependencies=[DependCustomerAuth])
async def do_orders_receive_delete(
        data_id: str = Query("", description="IDs"),
):
    user_id = CTX_USER_ID.get()
    data_ids = data_id.split(',')
    q = Q(user_id=user_id)
    q &= Q(id__in=data_ids)
    await orders_car_controller.do_delete(search=q)
    return Success(msg="删除成功")
